package com.qc.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.qc.controller.UserCookie;
import com.qc.entity.MerchantEntity;
import com.qc.entity.SystemEntity;
import com.qc.service.MerchantService;
import com.qc.service.SysTemService;

public class MerInterceptor extends HandlerInterceptorAdapter{

    
    @Resource
    private MerchantService merchantService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
        MerchantEntity merchantEntity = (MerchantEntity) request.getSession().getAttribute("merchantEntity");
        if (merchantEntity == null) {
            
          //判断Cookie是否存在该IP
            UserCookie cookies = new UserCookie();
            String ip = getIpAddr(request);
            Cookie cookie=cookies.getCookieByName(request, "merAutouser");
            if(cookie!=null){
                String usrpwd=cookie.getValue();
                String[] s1=usrpwd.split("-&&&&&&",3);
                String ip2=s1[0];
                String name=s1[1];
                String password=s1[2];
                if(ip==ip2||ip.equals(ip2)){
                    merchantEntity = merchantService.loginMerchant(name, password);
                    if(merchantEntity!=null){
                        request.getSession().setAttribute("merchantEntity", merchantEntity);
                    }
                }
            }else{
                request.getRequestDispatcher("/merIndex.jsp").forward(request, response); 
                return false;
            }
        }
        return true;
    }
    
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
